<template>
  <view class="supply-demand-page">
    <!-- 顶部导航栏 -->
    <view class="navbar">
      <view class="title"></view>
      <view class="publish-btn" @click="navigateToPublish">
        <u-icon name="plus-circle" size="24" color="#999"></u-icon>
        <text class="publish-text">发布</text>
      </view>
    </view>

    <!-- 搜索栏 -->
    <view class="search-container">
      <u-icon name="search" size="24" color="#999"></u-icon>
      <input 
        type="text" 
        placeholder="搜索供需信息..." 
        v-model="searchKeyword"
        class="search-input"
        @input="handleSearch"
      ></input>
    </view>

    <!-- 类型切换 -->
    <view class="type-tabs">
      <view 
        class="tab-item" 
        :class="{ active: currentType === 'all' }"
        @click="switchType('all')"
      >
        <text class="tab-text">全部</text>
      </view>
      <view 
        class="tab-item" 
        :class="{ active: currentType === 'supply' }"
        @click="switchType('supply')"
      >
        <text class="tab-text">供应</text>
      </view>
      <view 
        class="tab-item" 
        :class="{ active: currentType === 'demand' }"
        @click="switchType('demand')"
      >
        <text class="tab-text">需求</text>
      </view>
    </view>

    <!-- 筛选栏 -->
    <view class="filter-bar">
      <picker 
        class="filter-picker"
        mode="selector"
        :range="categories"
        :value="categoryIndex"
        @change="onCategoryChange"
      >
        <view class="picker-view">
          <text class="picker-text">{{ categories[categoryIndex] || '所有类型' }}</text>
          <u-icon name="arrow-down" size="24" color="#666"></u-icon>
        </view>
      </picker>
      
      <picker 
        class="filter-picker"
        mode="selector"
        :range="sortOptions"
        :value="sortIndex"
        @change="onSortChange"
      >
        <view class="picker-view">
          <text class="picker-text">{{ sortOptions[sortIndex] || '排序方式' }}</text>
          <u-icon name="arrow-down" size="24" color="#666"></u-icon>
        </view>
      </picker>
    </view>

    <!-- 帖子列表 -->
    <view class="posts-list">
      <view 
        class="post-item" 
        v-for="(post, index) in posts" 
        :key="post.id || index"
        @click="viewPostDetail(posts,index)"
      >
        <!-- 帖子头部：类型和名称 -->
        <view class="post-header">
          <view class="post-type" :class="post.type === 'supply' ? 'supply-type' : 'demand-type'">
            <text class="type-text">{{ post.type === 'supply' ? '供应' : '需求' }}</text>
          </view>
          <text class="post-title">{{ post.name }}</text>
        </view>
        
        <!-- 帖子内容：图片和信息 -->
        <view class="post-content" v-if="post.images">
          <view class="post-images" v-if="post.images.split(';').length > 0">
            <image 
              :src="post.images.split(';')[0]" 
              mode="aspectFill"
              class="post-image"
              :alt="post.name"
            ></image>
            <view class="image-count" v-if="post.images.split(';').length > 1">
              <text>+{{ post.images.split(';').length - 1 }}</text>
            </view>
          </view>
          
          <view class="post-info">
            <view class="info-row">
              <text class="info-text">{{ post.categoryName }}</text>
            </view>
            
            <view class="info-row">
              <text class="info-text">数量: {{ post.quantity }}</text>
            </view>
            
            <view class="info-row">
              <text class="info-text price">{{ post.type === 'supply' ? '售价: ' : '预算: ' }}¥{{ post.price.toFixed(2) }}</text>
            </view>
            
            <view class="info-row">
              <text class="info-text">{{ post.region }}</text>
            </view>
            
            <view class="info-row">
              <text class="info-text">{{ formatTime(post.publishTime) }}</text>
            </view>
          </view>
        </view>
        
        <!-- 帖子底部：简介和联系方式 -->
        <view class="post-footer">
          <text class="post-desc">{{ post.description | ellipsis(20) }}</text>
          <view class="contact-btn" @click.stop="contactSeller(posts,index)">
            <u-icon name="phone" size="24" color="#fff"></u-icon>
            <text class="contact-text">联系</text>
          </view>
        </view>
      </view>
      
      <!-- 空状态 -->
      <view class="empty-state" v-if="posts.length === 0 && !isLoading">
        <text class="empty-text">暂无相关信息</text>
        <view class="empty-btn" @click="navigateToPublish">
          <text class="btn-text">发布信息</text>
        </view>
      </view>
      
      <!-- 加载状态 -->
      <view class="loading-state" v-if="isLoading">
        <text class="loading-text">加载中...</text>
      </view>
    </view>
    
    <!-- 加载更多 -->
    <view class="load-more" v-if="hasMore && !isLoading && posts.length > 0">
      <view class="load-more-btn" @click="loadMorePosts">
        <text>加载更多</text>
      </view>
    </view>
  </view>
</template>

<script>
export default {
  data() {
    return {
      // 帖子数据 - 直接显示从后端获取的数据
      posts: [],
      
      // 搜索和筛选条件
      searchKeyword: '',
      currentType: 'all', // all, supply, demand
      categories: ['所有类型'], // 从后台获取
      categoryIndex: 0,
      sortOptions: ['最新发布', '价格从低到高', '价格从高到低'],
      sortIndex: 0,
      
      // 分页和加载状态
      pageNum: 1,
      pageSize: 10,
      hasMore: true,
      isLoading: false,
      
      // 从后台获取的分类数据
      allCategories: []
    };
  },
  
  onLoad() {
    // 加载分类数据
    this.loadCategories();
    // 加载帖子数据
    this.loadPosts();
  },
  
  filters: {
    // 文本截断过滤器
    ellipsis(value, length) {
      if (!value) return '';
      if (value.length <= length) return value;
      return value.slice(0, length) + '...';
    }
  },
  
  methods: {
    // 加载分类数据
    async loadCategories() {
      try {
        const result = await this.$request('api/v1/classList', 'get');
        if (result.code === 200) {
          const categoryNames = result.data.map(item => item.name);
          this.allCategories = result.data; // 保存完整数据
          this.categories = ['所有类型', ...categoryNames];
        } else {
          console.error('获取分类失败:', result.msg);
        }
      } catch (error) {
        console.error('获取分类失败:', error);
      }
    },
    
    // 加载帖子数据
    async loadPosts() {
      if (this.isLoading) return;
      
      this.isLoading = true;
      
      try {
        // 构建请求参数
        const params = {
          pageNum: this.pageNum,
          pageSize: this.pageSize
        };
        
        // 添加筛选条件
        if (this.currentType !== 'all') {
          params.type = this.currentType;
        }
        if (this.categoryIndex > 0) {
          params.categoryId = this.allCategories[this.categoryIndex - 1]?.id;
        }
        if (this.searchKeyword) {
          params.name = this.searchKeyword;
        }
        
        // 添加排序参数
        switch (this.sortIndex) {
          case 1: // 价格从低到高
            params.sortBy = 'price';
            params.order = 'asc';
            break;
          case 2: // 价格从高到低
            params.sortBy = 'price';
            params.order = 'desc';
            break;
          default: // 最新发布
            params.sortBy = 'publishTime';
            params.order = 'desc';
        }
        
        // 发送请求
        const result = await this.$request('api/v1/supplyDemands', 'get', params);
        
        if (result.code === 200) {
          const newPosts = result.rows || [];
          
          // 添加到现有列表
          if (this.pageNum === 1) {
            this.posts = newPosts;
          } else {
            this.posts = [...this.posts, ...newPosts];
          }
          
          // 检查是否还有更多数据
          this.hasMore = this.pageNum * this.pageSize < result.total;
        } else {
          console.error('获取帖子失败:', result.msg);
          uni.showToast({
            title: result.msg || '获取数据失败',
            icon: 'none'
          });
        }
      } catch (error) {
        console.error('获取帖子失败:', error);
        uni.showToast({
          title: '网络错误，请稍后重试',
          icon: 'none'
        });
		this.isLoading = false;
      } finally {
        this.isLoading = false;
      }
	  this.isLoading = false;
    },
    
    // 格式化时间
    formatTime(timeStr) {
      if (!timeStr) return '';
      
      try {
        const date = new Date(timeStr);
        const now = new Date();
        const diff = now - date;
        const days = Math.floor(diff / (24 * 60 * 60 * 1000));
        const hours = Math.floor(diff / (60 * 60 * 1000));
        const minutes = Math.floor(diff / (60 * 1000));
        
        if (days > 0) {
          return `${days}天前`;
        } else if (hours > 0) {
          return `${hours}小时前`;
        } else if (minutes > 0) {
          return `${minutes}分钟前`;
        } else {
          return '刚刚';
        }
      } catch (e) {
        return timeStr;
      }
    },
    
    // 搜索处理
    handleSearch() {
      this.pageNum = 1; // 修复变量名
      this.loadPosts();
    },
    
    // 切换类型
    switchType(type) {
      this.currentType = type;
      this.pageNum = 1; // 修复变量名
      this.loadPosts();
    },
    
    // 分类变化
    onCategoryChange(e) {
      this.categoryIndex = parseInt(e.detail.value);
      this.pageNum = 1; // 修复变量名
      this.loadPosts();
    },
    
    // 排序变化
    onSortChange(e) {
      this.sortIndex = parseInt(e.detail.value);
      this.pageNum = 1; // 修复变量名
      this.loadPosts();
    },
    
    // 加载更多
    loadMorePosts() {
      if (!this.hasMore || this.isLoading) return;
      
      this.pageNum++; // 修复变量名
      this.loadPosts();
    },
    
    // 查看帖子详情 - 添加参数验证
    viewPostDetail(posts,index) {
      // 验证post对象和id是否存在
      if (!posts || !posts[index].id) {
        uni.showToast({
          title: '帖子信息不完整',
          icon: 'none'
        });
        return;
      }
      
      uni.navigateTo({
        url: `/pages/supplyDemand/supplyDemandDetail?id=${posts[index].id}`
      });
    },
    
    // 联系发布者 - 添加参数验证
    contactSeller(posts,index) {
      // 检查post和post.phone是否存在
      if (!posts || !posts[index].phone) {
        uni.showToast({
          title: '电话号码不可用',
          icon: 'none'
        });
        return;
      }
      
      // 验证手机号格式
      const phoneRegex = /^1[3-9]\d{9}$/;
      if (!phoneRegex.test(posts[index].phone)) {
        uni.showToast({
          title: '电话号码格式不正确',
          icon: 'none'
        });
        return;
      }
      
      uni.makePhoneCall({
        phoneNumber: posts[index].phone,
        fail: (err) => {
          console.log('拨打电话失败', err);
          uni.showToast({
            title: '无法拨打电话',
            icon: 'none'
          });
        }
      });
    },
    
    // 跳转到发布页面
    navigateToPublish() {
      uni.navigateTo({
        url: '/pages/supplyDemand/publish'
      });
    }
  }
};
</script>

<style lang="scss" scoped>
.supply-demand-page {
  background-color: #f5f5f7;
  min-height: 100vh;
  font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
}

// 导航栏样式
.navbar {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 20rpx 30rpx;
  background-color: #2F85FC;
  color: #fff;

  .title {
    font-size: 36rpx;
    font-weight: 500;
    flex: 1;
    text-align: center;
  }

  .publish-btn {
    display: flex;
    align-items: center;
    background-color: #fff;
    color: #1677FF;
    padding: 8rpx 20rpx;
    border-radius: 20rpx;

    .publish-text {
      font-size: 26rpx;
      font-weight: 500;
      margin-left: 5rpx;
    }
  }
}

// 搜索栏样式
.search-container {
  display: flex;
  align-items: center;
  background-color: #fff;
  padding: 15rpx 20rpx;
  margin: 15rpx;
  border-radius: 30rpx;
  box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.05);

  .search-icon {
    margin-right: 10rpx;
  }

  .search-input {
    flex: 1;
    font-size: 28rpx;
    color: #333;
    background: transparent;
    border: none;
    outline: none;
    height: 40rpx;
    line-height: 40rpx;
  }
}

// 类型切换标签
.type-tabs {
  display: flex;
  background-color: #fff;
  border-bottom: 1px solid #eee;

  .tab-item {
    flex: 1;
    height: 90rpx;
    display: flex;
    align-items: center;
    justify-content: center;
    position: relative;

    .tab-text {
      font-size: 30rpx;
      color: #666;
    }

    &.active {
      .tab-text {
        color: #1677FF;
        font-weight: 500;
      }

      &:after {
        content: '';
        position: absolute;
        bottom: 0;
        left: 0;
        right: 0;
        height: 4rpx;
        background-color: #1677FF;
      }
    }
  }
}

// 筛选栏样式
.filter-bar {
  display: flex;
  background-color: #fff;
  padding: 15rpx 20rpx;
  border-bottom: 1px solid #eee;

  .filter-picker {
    flex: 1;
    padding: 0 10rpx;
  }

  .picker-view {
    display: flex;
    align-items: center;
    font-size: 26rpx;
    color: #666;

    .picker-icon {
      margin-right: 8rpx;
    }

    .picker-arrow {
      margin-left: 8rpx;
    }
  }
}

// 帖子列表样式
.posts-list {
  padding: 15rpx;
}

.post-item {
  background-color: #fff;
  border-radius: 16rpx;
  padding: 20rpx;
  margin-bottom: 15rpx;
  box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.05);
  transition: transform 0.2s;

  &:active {
    transform: scale(0.99);
  }

  .post-header {
    display: flex;
    align-items: center;
    margin-bottom: 15rpx;

    .post-type {
      padding: 5rpx 15rpx;
      border-radius: 15rpx;
      font-size: 24rpx;
      margin-right: 10rpx;

      .type-text {
        color: #fff;
      }
    }

    .supply-type {
      background-color: #4cd964;
    }

    .demand-type {
      background-color: #ff7e5f;
    }

    .post-title {
      font-size: 30rpx;
      color: #333;
      font-weight: 500;
      flex: 1;
      white-space: nowrap;
      overflow: hidden;
      text-overflow: ellipsis;
    }
  }

  .post-content {
    display: flex;
    margin-bottom: 15rpx;

    .post-images {
      width: 160rpx;
      height: 160rpx;
      border-radius: 8rpx;
      overflow: hidden;
      position: relative;

      .post-image {
        width: 100%;
        height: 100%;
        display: block;
      }

      .image-count {
        position: absolute;
        bottom: 5rpx;
        right: 5rpx;
        background-color: rgba(0, 0, 0, 0.5);
        color: #fff;
        font-size: 22rpx;
        padding: 2rpx 8rpx;
        border-radius: 10rpx;
      }
    }

    .post-info {
      flex: 1;
      margin-left: 20rpx;
      display: flex;
      flex-direction: column;
      justify-content: space-between;

      .info-row {
        display: flex;
        align-items: center;
        margin-bottom: 8rpx;

        .info-icon {
          margin-right: 8rpx;
        }

        .info-text {
          font-size: 24rpx;
          color: #666;
        }

        .price {
          color: #ff4d4f;
        }
      }
    }
  }

  .post-footer {
    display: flex;
    align-items: center;
    justify-content: space-between;

    .post-desc {
      font-size: 26rpx;
      color: #666;
      flex: 1;
      line-height: 1.4;
    }

    .contact-btn {
      background-color: #1677FF;
      color: #fff;
      padding: 8rpx 20rpx;
      border-radius: 20rpx;
      display: flex;
      align-items: center;
      font-size: 26rpx;
      margin-left: 10rpx;

      .contact-icon {
        margin-right: 5rpx;
      }
    }
  }
}

// 空状态样式
.empty-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 100rpx 0;

  .empty-text {
    font-size: 28rpx;
    color: #999;
    margin: 30rpx 0;
  }

  .empty-btn {
    background-color: #1677FF;
    color: #fff;
    padding: 12rpx 30rpx;
    border-radius: 30rpx;
    font-size: 28rpx;
  }
}

// 加载状态
.loading-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 80rpx 0;

  .loading-text {
    font-size: 28rpx;
    color: #666;
    margin-top: 20rpx;
  }
}

// 加载更多
.load-more {
  display: flex;
  justify-content: center;
  padding: 30rpx 0;

  .load-more-btn {
    padding: 12rpx 30rpx;
    border: 1px solid #ddd;
    border-radius: 30rpx;
    font-size: 26rpx;
    color: #666;
  }
}
</style>



